<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-10-18 14:00:41
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceVoucherRepository;
use App\Traits\AttachmentTrait;
use App\Traits\AutoCodeTrait;
use App\Traits\VoucherTrait;

class ComprehensiveCarry extends BaseModel
    {
    use AutoCodeTrait;
    use AttachmentTrait;
    use VoucherTrait;
    public $timestamps = true;
    public $table = "sys_comprehensive_carry";
    protected $guarded = [];
    //附件
    public $attachmentkey = "code";

    /**
     * 标识
     *
     * @var string
     */
    protected $ACSign = 'CARRY';

    /**
     * 编号所用的字段
     *
     * @var string
     */
    protected $ACCode = 'code';
    public function department()
        {
        return $this->belongsTo(Department::class);
        }
    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function company()
        {
        return $this->belongsTo(Company::class);
        }
    public function details()
        {
        return $this->hasMany(ComprehensiveCarryDetails::class, "main_id");
        }
    public function finance($model = null)
        {
        $v = $model ?? $this;

        if ($v->status_id == 2)
            return $v->voucher;
        if ($v->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }


        $last_amount = 0;
        $details     = [];
        $count       = $v->details->count();
        //运输数量是0的
        if ($v->quantity == 0) {
            $details[] = FinanceVoucherRepository::mergeVoucher(410111, $v->finance_remark, $v->amount, 0, ['department_id' => 33]);
            }
        else {
            //均价
            $price = $v->amount / $v->quantity;
            $v->details->filter(function ($vv, $k) use (&$last_amount, &$details, $v, $price, $count)
                {
                //销售 是费用，其他成本
                if ($vv->source_model == 'App\Models\MarketRetailDetails') {
                    $subject              = "560106";
                    $financedepartment_id = $vv->source->creator->department_id;
                    $financedepartment_id = $financedepartment_id == 0 ? 33 : $financedepartment_id;
                    }
                else {
                    $subject              = "410111";
                    $financedepartment_id = '33';
                    }

                $amount = round($price * $vv->quantity, 2);
                //最后一笔挤出金额
                if ($k + 1 == $count) {
                    $amount = $v->amount - $last_amount;
                    }
                else {
                    $last_amount += $amount;
                    }
                $details[] = FinanceVoucherRepository::mergeVoucher($subject, $v->finance_remark, $amount, 0, array_merge($vv->toArray(), [
                    'department_id' => $financedepartment_id,
                ]));
                });
            }
        $details[] = FinanceVoucherRepository::mergeVoucher(2202, $v['summary'], 0, $v->amount, $v->toArray());

        $voucher = FinanceVoucherRepository::CreateVoucher($v->billdate ?? $v->created_at, 1, $details, $v, $v->voucher?->id);
        //审核凭证
        fauditSave($v);

        return FinanceVoucherRepository::auditVoucher($voucher);
        }
    }
